package com.zhiwang.xiaoqu.aop

import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.zhiwang.xiaoqu.BuildConfig
import com.zhiwang.xiaoqu.R
import com.zhiwang.xiaoqu.mvp.model.sharepref.PrefManager
import com.zhiwang.xiaoqu.ui.BaseFragment
import com.zhiwang.xiaoqu.ui.LoginActivity
import com.zhiwang.xiaoqu.viewmodel.NetWorkViewModel
import com.zhiwang.xiaoqu.widget.Toasty
import org.aspectj.lang.ProceedingJoinPoint
import org.aspectj.lang.annotation.Around
import org.aspectj.lang.annotation.Aspect
import quickStartActivity

//network annotation for methods that associated withDrawPresenter network
@Target(AnnotationTarget.FUNCTION)
annotation class NetWorkRequired

@Target(AnnotationTarget.FUNCTION)
annotation class LoginRequired

@Aspect
open class NetWorkAspect {

    private val TAG = "NetWorkAspectEx"

    @Around("execution(@com.hiray.aop.net.NetWorkRequired  * *(..))")
    @Throws(Throwable::class)
    fun networkRequired(proceedingJoinPoint: ProceedingJoinPoint) {
        if (NetWorkViewModel.connected)
            proceedingJoinPoint.proceed()
        else
            Toasty.message(R.string.network_error_serious_hint)
    }
}


@Aspect
open class LoginAspect {
    private val TAG = "NetWorkAspectEx"

    @Around("execution(@com.hiray.aop.net.LoginRequired  * *(..))")
    @Throws(Throwable::class)
    fun loginRequired(jp: ProceedingJoinPoint) {
        if (BuildConfig.DEBUG)
            Log.i(TAG, "loginRequired 拦截: ${jp.target}   ${jp.`this`}  ${jp.signature}")
        if (PrefManager.isLoginValid().not()) {
            if (jp.`this` is BaseFragment) {
                var fragment = jp.`this` as BaseFragment
                fragment.quickStartActivity(LoginActivity::class.java)
            } else if (jp.`this` is AppCompatActivity) {
                var activity = jp.`this` as AppCompatActivity
                activity.quickStartActivity(LoginActivity::class.java)
            }
        } else jp.proceed()
    }
}
